<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small">
          <el-option
            v-for="dict in dict.type.cms_blog_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['blog:blog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:blog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:blog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['blog:blog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="types">
        <template slot-scope="scope">
          <el-tag size="mini" v-for="tag in scope.row.types" :key="tag.typeId" type="info">{{tag.typeName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tags">
        <template slot-scope="scope">
          <el-tag effect="plain" size="mini" v-for="tag in scope.row.tags" :key="tag.tagId" type="success">
            {{tag.tagName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阅读" align="center" prop="views" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cms_blog_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="首页图片" align="center" prop="blogPicUrl">
        <template slot-scope="scope">
          <ImagePreview
            :width=100 :height=100
            :src="scope.row.blogPicUrl"
            :preview-src-list="[scope.row.blogPicUrl]"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['blog:blog:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-folder-opened"
            @click="blogFiles(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >附件管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-folder-opened"
            @click="fileList(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >资源列表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改博客信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-row>
          <el-col :span="20">
            <el-form-item label="首页图片" prop="blogPicUrl">
              <el-input :maxlength="50" v-model="form.blogPicUrl" placeholder="首页图片"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleImage"
              v-hasPermi="['system:oss:upload']"
            >上传图片
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="首页图片">
              <ImagePreview
                :width=100 :height=100
                :src="form.blogPicUrl"
                :preview-src-list="[form.blogPicUrl]"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="简介">
              <el-input
                type="textarea"
                v-model="form.blogDesc"
                :autosize="{ minRows: 7, maxRows: 7}"
                maxlength="50"
                show-word-limit
                placeholder="请输入简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容">
          <blog-editor
            v-model="form.content"
            @getOssId="getOssId"
            :min-height="192" />
        </el-form-item>
        <el-form-item label="标签">
          <el-checkbox-group v-model="form.tagIds">
            <el-checkbox v-for="item in tagOptions" :label="item.tagId" :key="item.tagId" :value="item.tagId">
              {{item.tagName}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row>
          <el-col :span="7">
            <el-form-item label="分类">
              <el-select v-model="form.typeIds" multiple placeholder="请选择" filterable clearable>
                <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item label="置顶">
              <el-checkbox v-model="top"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="releaseForm">发 布</el-button>
        <el-button :loading="buttonLoading" type="info" @click="saveForm">暂 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :title="imageTitle" :visible.sync="imageOpen" width="500px" append-to-body>
      <el-form ref="form" :model="imageForm" :rules="imageRules" label-width="80px">
        <el-form-item label="文件名">
          <imageUpload v-model="imageForm.file" :limit="1" @fileList="getImageUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="imageButtonLoading" type="primary" @click="submitImageForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 资源列表对话框 -->
    <el-dialog :title="fileTitle" :visible.sync="fileListOpen" width="1000px" append-to-body>
      <el-table class="file-list" :data="fileInfoList">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="文件主键id" align="center" prop="ossId" /> -->
        <el-table-column label="图片预览" align="center" prop="url">
          <template slot-scope="scope">
            <el-image style="width: 120px;height: 60px;" :src="scope.row.url" lazy :preview-src-list="[scope.row.url]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" align="center" prop="originalName" />
        <el-table-column label="文件类型" align="center" prop="fileSuffix" />
        <!-- <el-table-column label="存储文件名称" align="center" prop="fileObjectName" /> -->
        <!-- <el-table-column label="存储路径" align="center" prop="filePath" /> -->
        <el-table-column label="创建者" align="center" prop="createBy" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 附件管理对话框 -->
    <el-dialog title="附件管理" :visible.sync="blogFilesOpen" :before-close="fileCancel" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
        <el-form-item>
          <el-row>
            <el-button size="mini" type="primary" @click="addFiles">添加文件</el-button>
            <el-table :data="form.blogFilesNew" :border="true" style="width: 99.99%;">
              <el-table-column align="center" min-width="20%" prop="pic" label="附件">
                <template slot-scope="scope">
                  <FileUpload v-model="scope.row.ossId" @fileList="getFileList" :is-show-tip="false" />
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="20%" prop="remark" label="文件信息">
                <template slot-scope="scope">
                  <el-row>
                    <el-col :span="6"><div class="blogFilesInfoName">名称：</div></el-col>
                    <el-col :span="18"><el-input v-model="scope.row.name" disabled/></el-col>
                  </el-row>
                  <el-row style="margin-top: 4px;">
                    <el-col :span="6"><div class="blogFilesInfoName">地址：</div></el-col>
                    <el-col :span="18"><el-input v-model="scope.row.url" disabled/></el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="20%" label="操作">
                <template slot-scope="scope">
                  <el-button v-show="scope.row.ossId!==''" size="mini" plain @click="handleDownload(scope.row)">下载</el-button>
                  <el-button size="mini" type="danger" plain @click="delFiles(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveBlogFiles">保 存</el-button>
        <el-button @click="fileCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBlog, getBlog, delBlog, addBlog, updateBlog, getAllTagAndAllType } from "@/api/blog/blog";
import { addBatch, getFileList } from "@/api/blog/blogFile";
import { Loading } from 'element-ui';

export default {
  name: "Blog",
  dicts: ['cms_blog_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 默认排序
      defaultSort: {prop: 'Top,createTime', order: 'descending,descending'},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 博客信息表格数据
      blogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        type: 1,
        status: undefined
      },
      top: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ]
      },
      fileIds: [],
      // 类型选项
      typeOptions: [],
      // 标签选项
      tagOptions: [],
      // 按钮loading
      imageButtonLoading: false,
      // 弹出层标题
      imageTitle: "",
      // 是否显示弹出层
      imageOpen: false,
      // 表单参数
      imageForm: {},
      // 表单校验
      imageRules: {
        file: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ]
      },
      // 弹出层标题
      fileTitle: "",
      // 是否显示弹出层
      fileListOpen: false,
      // 资源列表表格数据
      fileInfoList: [],
      blogFilesOpen: false,
    };
  },
  created() {
    this.queryParams.orderByColumn = this.defaultSort.prop;
    this.queryParams.isAsc = this.defaultSort.order;
    this.getList();
    getAllTagAndAllType().then(response => {
      this.typeOptions = response.data.types;
      this.tagOptions = response.data.tags;
    });
  },
  methods: {
    /** 查询博客信息列表 */
    getList() {
      this.loading = true;
      listBlog(this.queryParams).then(response => {
        this.blogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        type: 1,
        content: undefined,
        top: "0",
        blogPicOssId: undefined,
        blogPicUrl: undefined,
        blogPicName: undefined,
        blogDesc: undefined,
        tagIds: [],
        typeIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加博客信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getBlog(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改博客信息";
      });
    },
    /** 发布按钮 */
    releaseForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.type = 1;
          this.form.status = 1;
          if (this.top) {
            this.form.top = 1;
          } else {
            this.form.top = 0;
          }
          if (this.form.id != null) {
            updateBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: this.form.id,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: response.data,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 暂存按钮 */
    saveForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.type = 1;
          this.form.status = 0;
          if (this.top) {
            this.form.top = 1;
          } else {
            this.form.top = 0;
          }
          if (this.form.id != null) {
            updateBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: this.form.id,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: response.data,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除博客信息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delBlog(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('blog/blog/export', {
        ...this.queryParams
      }, `blog_${new Date().getTime()}.xlsx`)
    },
    getOssId(data) {
      this.fileIds.push(data);
    },
    // 表单重置
    resetImage() {
      this.imageForm = {
        file: undefined,
      };
      this.resetForm("imageForm");
    },
    /** 图片按钮操作 */
    handleImage() {
      this.resetImage();
      this.imageOpen = true;
      this.imageTitle = "上传图片";
    },
    /** 提交按钮 */
    submitImageForm() {
      this.imageOpen = false;
    },
    getImageUrl(fileList){
      if(fileList.length == 1){
        this.form.blogPicOssId = fileList[0].ossId;
        this.form.blogPicUrl = fileList[0].url;
        this.form.blogPicName = fileList[0].name;
      }else{
        this.form.blogPicOssId = "";
        this.form.blogPicUrl = "";
        this.form.blogPicName = "";
      }
    },
    /** 资源列表按钮操作 */
    fileList(row) {
      let loadingInstance = Loading.service({
        target: ".file-list"
      });
      this.reset();
      const blogId = row.id || this.ids
      getFileList(blogId).then(response => {
        this.fileInfoList = response.data;
        this.fileListOpen = true;
        this.fileTitle = "资源列表";
        setTimeout(() => {
          loadingInstance.close();
        }, 100);
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      this.$download.oss(row.ossId)
    },
    /** 附件管理按钮操作 */
    blogFiles(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getBlog(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.blogFilesNew = []
        if (response.data.blogFiles !== null) {
          this.form.blogFilesNew = JSON.parse(response.data.blogFiles)
        }
        if (this.form.top == 1) {
          this.top = true;
        };
        this.blogFilesOpen = true;
      });
    },
    // 取消按钮
    fileCancel() {
      this.blogFilesOpen = false;
      this.reset();
    },
    // 生成uuid
    uuid() {
      var d = new Date().getTime()
      if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now() // use high-precision timer if available
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random() * 16) % 16 | 0 // d是随机种子
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
      })
      return uuid
    },
    // 附件管理添加按钮
    addFiles() {
      this.form.blogFilesNew.push(
        {
          id: this.uuid(),
          ossId: '',
          name: '',
          url: ''
        })
    },
    delFiles(index, row) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定的操作(调用接口)
        var hasmembers = this.form.blogFilesNew
        for (var i = 0; i < hasmembers.length; i++) {
          if (row.id === hasmembers[i].id) {
            this.form.blogFilesNew.splice(i, 1)
          }
        }
      }).catch(() => {
        // 点取消的提示
        return
      })
    },
    getFileList(fileList){
      this.form.blogFilesNew.forEach(item => {
        fileList.forEach(file =>{
          if(item.ossId===file.ossId){
            item.name = file.name
            item.url = file.url
          }
        })
      });
    },
    //保存文件
    saveBlogFiles(){
      if (this.form.blogFilesNew.length > 0) {
        for (let i = 0; i < this.form.blogFilesNew.length; i++) {
          const fileInfo = this.form.blogFilesNew[i]
          if (fileInfo.ossId === '') {
            this.$message.warning('请添加文件或删除空行！')
            return false
          } else if (fileInfo.remark === '') {
            this.$message.warning('请添加文件备注！')
            return false
          }
        }
      }
      this.form.blogFiles = JSON.stringify(this.form.blogFilesNew)
      updateBlog(this.form).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.blogFilesOpen = false;
        this.getList();
      });
    },
  }
};
</script>
